package 二叉树;

import java.util.LinkedList;
import java.util.Queue;

public class q104二叉树的最大深度 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    class Solution {
        public int countNodes(TreeNode root) {
            if(root==null) return 0;
            return countNodes(root.left)+countNodes(root.right)+1;
        }
        // 迭代法
        public int countNodes2(TreeNode root) {
            if (root == null) return 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            int result = 0;
            while (!queue.isEmpty()) {
                int size = queue.size();
                while (size -- > 0) {
                    TreeNode cur = queue.poll();
                    result++;
                    if (cur.left != null) queue.offer(cur.left);
                    if (cur.right != null) queue.offer(cur.right);
                }
            }
            return result;
        }
    }

}
